package org.jeecg.modules.hotel.arrangement.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.bed.entity.LwgyBaseBed;
import org.jeecg.modules.basic.demo.bed.mapper.LwgyBaseBedMapper;
import org.jeecg.modules.basic.demo.bed.service.ILwgyBaseBedService;
import org.jeecg.modules.basic.demo.school.mapper.LwgyBaseSchoolMapper;
import org.jeecg.modules.basic.demo.student.entity.LwgyBaseStudent;
import org.jeecg.modules.basic.demo.student.service.ILwgyBaseStudentService;
import org.jeecg.modules.basic.iouser.controller.LwgyInoutUserController;
import org.jeecg.modules.hotel.arrangement.entity.ImportLwgyStu;
import org.jeecg.modules.hotel.arrangement.entity.ImportStuHotel;
import org.jeecg.modules.hotel.arrangement.entity.LwgyHotelArrangement;
import org.jeecg.modules.hotel.arrangement.service.ILwgyHotelArrangementService;
import org.jeecg.modules.hotel.arrangement.util.ExcelImport;
import org.jeecg.modules.hotel.history.entity.LwgyHotelHistory;
import org.jeecg.modules.hotel.history.mapper.LwgyHotelHistoryMapper;
import org.jeecg.modules.hotel.history.service.ILwgyHotelHistoryService;
import org.jeecg.modules.hotel.requisition.service.ILwgyHotelRequisitionService;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Description: 住宿分配管理
 * @Author: Aioe
 * @Date: 2021-02-24
 * @Version: V1.0
 */


//hotel/lwgyHotelArrangement/updateBedStu
@Api(tags = "住宿分配管理")
@RestController
@RequestMapping("/hotel/LwgyHotelArrangementHolidayController")
@Slf4j
public class LwgyHotelArrangementHolidayController extends JeecgController<LwgyHotelArrangement, ILwgyHotelArrangementService> {

    @Autowired
    private ILwgyHotelArrangementService lwgyHotelArrangementService;

    @Autowired
    private ILwgyHotelHistoryService lwgyHotelHistoryService;

    @Autowired
    private ILwgyBaseBedService lwgyBaseBedService;

    @Autowired
    private ILwgyBaseStudentService lwgyBaseStudentService;

    @Resource
    private LwgyBaseBedMapper lwgyBaseBedMapper;

    @Resource
    private LwgyBaseSchoolMapper lwgyBaseSchoolMapper;

    @Resource
    private LwgyHotelHistoryMapper lwgyHotelHistoryMapper;

    @Autowired
    private LwgyInoutUserController lwgyInoutUserController;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private ILwgyHotelRequisitionService lwgyHotelRequisitionService;


    /**
     * 调宿
     *
     * @param lwgyHotelArrangement
     * @return
     */
    @AutoLog(value = "调宿")
    @ApiOperation(value = "调宿", notes = "调宿")
    @PutMapping(value = "/updateBedHolidayStu")
    public Result<?> updateBedHolidayStu(@RequestBody LwgyHotelArrangement lwgyHotelArrangement) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
        List<String> roles = sysBaseAPI.getRolesByUsername(username);

 /*       if(roles.contains("fdy")){
            String studentId = lwgyHotelArrangement.getStudentId();
            LwgyBaseStudent student = lwgyBaseStudentService.getById(studentId);

            LwgyHotelRequisition lwgyHotelRequisition = new LwgyHotelRequisition();
            lwgyHotelRequisition.setAuditProcess("2");
            lwgyHotelRequisition.setFromUser(username);
            lwgyHotelRequisition.setToUser("admin");
            LwgyBaseBed lwgyBaseBed ;
            if(lwgyHotelArrangement.getBehavior().equals("choose_bed")){//如果是入住
                lwgyBaseBed = lwgyBaseBedService.getById(lwgyHotelArrangement.getAfterBed());
                lwgyHotelRequisition.setBedId(lwgyHotelArrangement.getAfterBed());
            }else {
                lwgyBaseBed = lwgyBaseBedService.getById(lwgyHotelArrangement.getBeforeBed());
                lwgyHotelRequisition.setBedId(lwgyHotelArrangement.getBeforeBed());
                lwgyHotelRequisition.setAfterBed(lwgyHotelArrangement.getAfterBed());
            }
            lwgyHotelRequisition.setUnitId(lwgyBaseBed.getRoomId());
            lwgyHotelRequisition.setStudentId(studentId);
            lwgyHotelRequisition.setProcessingState("0");
            lwgyHotelRequisition.setReason("辅导员请求审核!");
            lwgyHotelRequisition.setBehavioral(lwgyHotelArrangement.getBehavior());
//            lwgyHotelRequisition.setReason();
            lwgyHotelRequisition.setRoomsex(student.getStudentSex());
            QueryWrapper<LwgyRoomViews> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("room_id",lwgyBaseBed.getRoomId());
            String buildingId = lwgyHotelArrangementService.getBuildId(lwgyBaseBed.getRoomId());
            lwgyHotelRequisition.setBuildingId(buildingId);
            lwgyHotelRequisition.setStudentCampus(student.getStudentCampus());
            lwgyHotelRequisition.setStudentCollege(student.getStudentCollege());
            lwgyHotelRequisition.setStudentClass(student.getStudentClass());
            lwgyHotelRequisition.setStudentYear(student.getStudentYear());
            lwgyHotelRequisition.setStudentMajor(student.getStudentMajor());
            lwgyHotelRequisition.setStudentName(student.getStudentName());
            lwgyHotelRequisitionService.pushMsg(lwgyHotelRequisition,username,roles,student);
            lwgyHotelRequisitionService.save(lwgyHotelRequisition);

            //微信：
            lwgyHotelRequisitionService.pushWx(lwgyHotelRequisition,username,roles,student);
            return Result.OK("已将调宿信息推送给管理员",null);
        }*/

        String behavior = lwgyHotelArrangement.getBehavior();
        String type = "";
        if (behavior.equals("change_bed")) {//确认是调宿
            type = "调宿";
            lwgyHotelArrangement.setId(lwgyHotelArrangement.getBeforeBed());
            lwgyHotelArrangementService.checkOutStu(lwgyHotelArrangement);//退掉之前的床位
            try {
                List<LwgyBaseBed> bed = lwgyBaseBedMapper.getBedIdList(lwgyHotelArrangement.getAfterBed(), "bed");
                lwgyInoutUserController.iouserChange(lwgyHotelArrangement.getStudentId(), bed.get(0).getBuildingId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (behavior.equals("leave_bed")) {//如果行为是退宿
            type = "退宿";
            lwgyHotelArrangement.setId(lwgyHotelArrangement.getBeforeBed());//将变更之前的床位id给现在的id
        } else {//如果行为是调宿或者入住
            type = "入住";
            lwgyHotelArrangement.setId(lwgyHotelArrangement.getAfterBed());//将变更之后的床位id给现在的id
        }
        //辅导员调整宿舍，会给管理员推送消息
        if (roles.contains("fdy")) {
            lwgyHotelRequisitionService.pushChangeMsg(lwgyHotelArrangement, username, type);
        }
        lwgyHotelArrangementService.updateBedStu(lwgyHotelArrangement);
        LwgyHotelHistory lwgyHotelHistory = new LwgyHotelHistory();
        lwgyHotelHistory.setAfterBed(lwgyHotelArrangement.getAfterBed());
        lwgyHotelHistory.setBehavior(lwgyHotelArrangement.getBehavior());
        lwgyHotelHistory.setPersonId(lwgyHotelArrangement.getStudentId());
        lwgyHotelHistory.setBeforeBed(lwgyHotelArrangement.getBeforeBed());
        lwgyHotelHistoryService.save(lwgyHotelHistory);//保存历史记录
        return Result.OK("编辑成功!");
    }

    /**
     * 退宿
     *
     * @param lwgyHotelArrangement
     * @return
     */
    @AutoLog(value = "退宿")
    @ApiOperation(value = "退宿", notes = "退宿")
    @PutMapping(value = "/checkOutStuUrl")
    public Result<?> checkOutStu(@RequestBody LwgyHotelArrangement lwgyHotelArrangement) {
        System.out.println(lwgyHotelArrangement);
        //1. 退宿
        lwgyHotelArrangementService.checkOutStu(lwgyHotelArrangement);
        //2. 存储到历史记录
        LwgyHotelHistory lwgyHotelHistory = new LwgyHotelHistory();
        lwgyHotelHistory.setBeforeBed(lwgyHotelArrangement.getId());
        lwgyHotelHistory.setBehavior("leave_bed");
        lwgyHotelHistory.setPersonId(lwgyHotelArrangement.getStudentId());
        lwgyHotelHistory.setSort("");
        lwgyHotelHistoryService.save(lwgyHotelHistory);
        return Result.OK("编辑成功!");
    }

    /**
     * 批量退宿
     *
     * @param hotelArrangeList
     * @return
     */
    @AutoLog(value = "批量退宿")
    @ApiOperation(value = "批量退宿", notes = "批量退宿")
    @PutMapping(value = "/cleanBed")
    public Result<?> cleanBed(@RequestBody List<Map<String, String>> hotelArrangeList) {
        List<LwgyHotelHistory> arrangementList = new ArrayList<>();
        String ids = "";
        LwgyHotelHistory lwgyHotelHistory;
        for (Map<String, String> map : hotelArrangeList) {
            ids += map.get("beforeBed") + ",";
            lwgyHotelHistory = JSON.parseObject(JSON.toJSONString(map), LwgyHotelHistory.class);
            arrangementList.add(lwgyHotelHistory);
        }
        lwgyHotelArrangementService.cleanBed(ids);//批量清空住宿
        lwgyHotelHistoryService.saveBatch(arrangementList);//批量存储退宿记录
        return Result.OK("编辑成功!");
    }

    /**
     * 批量调宿、入住
     *
     * @param hotelArrangeList
     * @return
     */
    @AutoLog(value = "批量调宿、入住")
    @ApiOperation(value = "批量调宿、入住", notes = "批量调宿、入住")
    @PutMapping(value = "/batchUpdateBedStu")
    public Result<?> batchUpdateBedStu(@RequestBody List<Map<String, String>> hotelArrangeList) {
        List<LwgyHotelHistory> arrangementList = new ArrayList<>();
        String beforeBed = "";
        String afterBed = "";
        LwgyBaseBed lwgyBaseBed;
        List<LwgyBaseBed> bedList = new ArrayList<>();
        LwgyHotelHistory lwgyHotelHistory;
        String behavior = hotelArrangeList.get(0).get("behavior");
        if (behavior.equals("change_bed")) {//如果是调宿，需要先清空住宿信息
            for (Map<String, String> map : hotelArrangeList) {
                beforeBed += map.get("beforeBed") + ",";
            }
            lwgyHotelArrangementService.cleanBed(beforeBed);//批量清空原来的住宿信息
        }
        for (Map<String, String> map : hotelArrangeList) {//
            lwgyBaseBed = new LwgyBaseBed();
            lwgyBaseBed.setId(map.get("afterBed"));
            lwgyBaseBed.setStudentId(map.get("personId"));
            bedList.add(lwgyBaseBed);
            lwgyHotelHistory = JSON.parseObject(JSON.toJSONString(map), LwgyHotelHistory.class);
            arrangementList.add(lwgyHotelHistory);//创建历史记录实体的集合
        }
        lwgyBaseBedService.updateBatchById(bedList);//更新入住信息
//        lwgyBaseBedService.saveBatch(bedList);
        lwgyHotelHistoryService.saveBatch(arrangementList);//保存历史记录
        return Result.OK("编辑成功!");
    }


    /**
     * 批量分配床位
     *
     * @param hotelArrangeList
     * @return
     */
    @AutoLog(value = "批量分配床位")
    @ApiOperation(value = "批量分配床位", notes = "批量分配床位")
    @PutMapping(value = "/batchAllot")
    public Result<?> batchAllot(@RequestBody Map<String, String> hotelArrangeList) {
        System.out.println("hotelArrangeList = " + hotelArrangeList);
        lwgyHotelArrangementService.batchAllot(hotelArrangeList);
        return Result.OK("操作成功!");
    }
    /**
     * 批量离校
     *
     * @param hotelArrangeList
     * @return
     */
   /* @AutoLog(value = "批量离校")
    @ApiOperation(value = "批量离校", notes = "批量离校")
    @PostMapping(value = "/leaveSchool")
    public Result<?> leaveSchool(@RequestParam(name="ids",required=true) String ids) {
        String[] arr = ids.split(",");
        System.out.println(Arrays.toString(arr));
        List<LwgyHotelHistory> arrangementList = new ArrayList<>();
        LwgyHotelHistory lwgyHotelHistory;
        for (String string : arr) {
            ids += "beforeBed" + ",";
            lwgyHotelHistory = JSON.parseObject(string, LwgyHotelHistory.class);
            arrangementList.add(lwgyHotelHistory);
        }
        lwgyHotelArrangementService.leaveSchool(ids);//批量离校
        lwgyHotelArrangementService.cleanBed(ids);//批量清空住宿
        lwgyHotelHistoryService.saveBatch(arrangementList);//批量存储退宿记录
        return Result.OK("编辑成功!");
    }*/

    /**
     * 根据id获去权限，用于下发分配床位
     */
    @AutoLog(value = "根据id获去权限，用于下发分配床位")
    @ApiOperation(value = "根据id获去权限，用于下发分配床位", notes = "根据id获去权限，用于下发分配床位")
    @GetMapping(value = "/getPermissionById")
    public Result<?> getPermissionById(@RequestParam(name = "id") String id) {
        List<String> roles = lwgyBaseBedService.getRoleById(id);
        if (roles.contains("admin")) {//角色是超级管理员
            return Result.OK("1");
        } else if (roles.contains("xld")) {//角色是校领导
            return Result.OK("2");
        } else {
            return Result.OK(3);
        }
    }

    /**
     * 批量离校
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "批量离校")
    @ApiOperation(value = "批量离校", notes = "批量离校")
    @PostMapping(value = "/leaveSchool")
    public Result<?> leaveSchool(@RequestBody String ids) {
        List<LwgyHotelHistory> arrangementList = lwgyHotelArrangementService.leaveBedHistory(ids);
        System.out.println(ids);
        if (oConvertUtils.isNotEmpty(ids)) {
            if (ids.length() > 11) {
                ids = ids.substring(8, ids.length() - 2);
                lwgyHotelArrangementService.leaveSchool(ids);//批量离校
                lwgyHotelArrangementService.cleanBed(ids);//批量清空住宿
                lwgyHotelHistoryService.saveBatch(arrangementList);//批量存储退宿记录
                return Result.OK("编辑成功!");
            }
        }
        return Result.error("错误！");

    }

    /**
     * 查询学生可选择的房间
     *
     * @param studentId
     * @return
     */
    @GetMapping("/studentChooseBedList")
    public Result<?> studentChooseBedList(@RequestParam(name = "studentId", required = false, defaultValue = "1385586453517447177") String studentId) {
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        String id = sysUser.getId();

        LwgyBaseStudent lwgyBaseStudent = lwgyBaseStudentService.getById(studentId);
        String studentClass = lwgyBaseStudent.getStudentClass();
        boolean b = lwgyHotelArrangementService.getClassOpenTime(studentClass);
        if (!b) {
            return new Result<>().error500("未到选房时间！");
        }
        LwgyBaseBed lwgyBaseBed = new LwgyBaseBed();
        lwgyBaseBed.setStudentClass(studentClass);
        lwgyBaseBed.setRoomSex(lwgyBaseStudent.getStudentSex());
        QueryWrapper<LwgyBaseBed> queryWrapper = QueryGenerator.initQueryWrapper(lwgyBaseBed, null);
        Page<LwgyBaseBed> page = new Page<>(0, 100);
        queryWrapper.orderByAsc("name");
        IPage<LwgyBaseBed> pageList = lwgyBaseBedService.queryPageListCustom(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 学生自选床位
     *
     * @param lwgyBaseBed
     * @return
     */
    @ApiOperation("学生自选床位")
    @PutMapping("/studentChooseBed")
    public Result<?> studentChooseBed(@RequestBody LwgyBaseBed lwgyBaseBed) {
        String lockKey = "choose_bed";
        String clientId = UUID.randomUUID().toString();
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clientId, 30, TimeUnit.SECONDS);//redis分布式锁 30s 过期
        if (!result) {
            return Result.error("前方拥堵，请重试");
        }
        try {
            if (oConvertUtils.isEmpty(lwgyBaseBed.getId())) {
                return Result.error("未选择床位");
            }
            QueryWrapper<LwgyBaseBed> queryWrapper = new QueryWrapper();
            LwgyBaseStudent lwgyBaseStudent = lwgyBaseStudentService.getById(lwgyBaseBed.getStudentId());//根据学生id获取学生信息
            String studentClass = lwgyBaseStudent.getStudentClass();//获取学生的班级
            boolean b = lwgyHotelArrangementService.getClassOpenTime(studentClass);//查看该班级是否在选房时间段
            if (!b) {
                return Result.error("未到选房时间！");
            }
            Object o = redisUtil.get(lwgyBaseStudent.getId());//通过学生id查询缓存中是否存在他的床位信息
            if (oConvertUtils.isNotEmpty(o)) {                  //不为空
                return Result.error("已经选择过床位");
            } else {                                            //缓存中不存在该学生的床位信息  再查db
                queryWrapper.eq("student_id", lwgyBaseBed.getStudentId());
                List list = lwgyBaseBedMapper.selectList(queryWrapper);//根据学生id查询床位信息
                if (oConvertUtils.listIsNotEmpty(list)) {//如果有值说明已经选过床位
                    System.out.println("lwgyBaseBed = " + lwgyBaseBed);
                    redisTemplate.opsForValue().set(lwgyBaseBed.getId(), lwgyBaseBed, 3, TimeUnit.DAYS);//将床位信息放入缓存
                    redisTemplate.opsForValue().set(lwgyBaseStudent.getId(), lwgyBaseBed, 3, TimeUnit.DAYS);//将该学生选择的床位加入缓存，三天过期
                    return Result.error("已经选择过床位");
                }
            }
            Object lwgyBed = redisUtil.get(lwgyBaseBed.getId());//查询缓存是否有该床位
            if (oConvertUtils.isNotEmpty(lwgyBed)) {
                return Result.error("该床位已被选！");
            } else {
                queryWrapper = new QueryWrapper<>();
                queryWrapper.select("student_id");
                queryWrapper.eq("id", lwgyBaseBed.getId());
                LwgyBaseBed lwgyBedStuID = lwgyBaseBedService.getOne(queryWrapper);//查询DB中该床位上是否已经有学生选择
                if (oConvertUtils.isNotEmpty(lwgyBedStuID)) {
                    if (oConvertUtils.isNotEmpty(lwgyBedStuID.getStudentId())) {
                        redisTemplate.opsForValue().set(lwgyBaseBed.getId(), lwgyBaseBed, 3, TimeUnit.DAYS);//将床位信息放入缓存
                        return Result.error("该床位已被选！");
                    }
                } else {
                    return Result.error("该床位不存在！");
                }
            }
            LwgyBaseBed lwgyBaseBedEntity = new LwgyBaseBed();
            lwgyBaseBedEntity.setId(lwgyBaseBed.getId());
            lwgyBaseBedEntity.setStudentId(lwgyBaseBed.getStudentId());
            int i = lwgyBaseBedMapper.updateById(lwgyBaseBedEntity);//向学生选择的床位上插入学生的信息
            if (i >= 1) {
                //选床位成功存历史记录
                redisTemplate.opsForValue().set(lwgyBaseStudent.getId(), lwgyBaseBed, 3, TimeUnit.DAYS);//将该学生选择的床位加入缓存，三天过期
                redisTemplate.opsForValue().set(lwgyBaseBed.getId(), lwgyBaseBed, 3, TimeUnit.DAYS);//将床位信息放入缓存
                LwgyHotelHistory lwgyHotelHistory = new LwgyHotelHistory();
                lwgyHotelHistory.setAfterBed(lwgyBaseBed.getId());
                lwgyHotelHistory.setBehavior("choose_bed");
                lwgyHotelHistory.setPersonId(lwgyBaseBed.getStudentId());
                lwgyHotelHistory.setCreateBy(lwgyBaseStudent.getStudentName());
                lwgyHotelHistoryMapper.insert(lwgyHotelHistory);
                return Result.OK("选房成功");
            }
        } finally {
            //只能释放自己的锁
            if (clientId.equals(stringRedisTemplate.opsForValue().get(lockKey))) {
                stringRedisTemplate.delete(lockKey);
            }
        }
        return Result.error("选房失败");
    }

    /**
     * 查询学生的床位
     *
     * @param studentId
     * @return
     */
    public Result getStudentBedByStudentId(String studentId) {
        List<LwgyBaseBed> lwgyBaseBeds = lwgyHotelArrangementService.getBedListByStudentId(studentId);
        return Result.OK(lwgyBaseBeds);
    }


    /**
     * 导出excel
     *
     * @param request
     * @param
     */
    @RequestMapping(value = "/outStuHotel")
    public ModelAndView outStuHotel(HttpServletRequest request, LwgyBaseBed lwgyBed) {
        List<ImportStuHotel> lwgyBaseBed = lwgyHotelArrangementService.outStuHotel(lwgyBed);
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        ImportStuHotel importStuHotel = new ImportStuHotel();
        mv.addObject(NormalExcelConstants.FILE_NAME, "住宿信息"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, ImportStuHotel.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("住宿信息", ""));
        mv.addObject(NormalExcelConstants.DATA_LIST, lwgyBaseBed);
        return mv;
    }

    /**
     * 导出excel模板
     *
     * @param request
     * @param
     */
    @RequestMapping(value = "/outStuTemplate")
    public ModelAndView outStuTemplate(HttpServletRequest request, LwgyBaseBed lwgyBed) {
        List<ImportStuHotel> lwgyBaseBed = new ArrayList<>(1);
        ImportStuHotel importStuHotel = new ImportStuHotel();
        importStuHotel.setCampusName("青岛校区(必填)");
        importStuHotel.setBuildingName("AB3(必填)");
        importStuHotel.setUnitName("1单元(必填)");
        importStuHotel.setLayerName("1层(必填)");
        importStuHotel.setRoomName("101(必填)");
        importStuHotel.setRoomOrientation("北(非必填)");
        importStuHotel.setRoomSex("男(非必填)");
        importStuHotel.setBedName("01(必填)");
        importStuHotel.setBedPrice("800(非必填)");
        importStuHotel.setStudentName("姓名(必填)");
        importStuHotel.setStudentNumber("202182080040(必填)");
        importStuHotel.setStudentClass("硕士研究生2021(非必填)");
        lwgyBaseBed.add(importStuHotel);
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "住宿信息"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, ImportStuHotel.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("住宿信息", ""));
        mv.addObject(NormalExcelConstants.DATA_LIST, lwgyBaseBed);
        return mv;
    }


    @ApiOperation(value = "床位批量绑定辅导员", notes = "床位批量绑定辅导员")
    @PutMapping("/bedBatchBindTeacher")
    public Result bedBatchBindTeacher(String bedIds, String teacherIds, String facultyId) {
        if (oConvertUtils.isEmpty(bedIds)) {
            return Result.error("请先选择床位!");
        }
        String[] bedId = bedIds.split(",");
        try {
            lwgyHotelArrangementService.bedBatchBindTeacher(Arrays.asList(bedId), teacherIds, facultyId);
        } catch (Exception e) {
            return Result.error("未知的错误,绑定失败!");
        }
        return Result.OK("绑定成功", null);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param
     */
    @RequestMapping(value = "/StuZsHotel")
    public void StuZsHotel(HttpServletRequest request, HttpServletResponse response, LwgyBaseBed lwgyBed) throws IOException {
        //获取所有床位信息。
        List<ImportStuHotel> lwgyBaseBed = lwgyHotelArrangementService.outStuHotel(lwgyBed);
        //获取最大床位数
        IntSummaryStatistics resultNum = lwgyBaseBed.stream().mapToInt((item) -> Integer.parseInt(item.getBedName())).summaryStatistics();
        Integer info = resultNum.getMax();
        //楼宇名字修改为楼名_房间名
        lwgyBaseBed.stream().forEach(r -> r.setBuildingName(r.getBuildingName() + "-" + r.getRoomName()));

        //获取每个房间的信息。
        LinkedHashMap<String, List<ImportStuHotel>> lwgyBaseBedT = lwgyBaseBed.stream()
                .collect(Collectors.groupingBy(ImportStuHotel::getBuildingName, LinkedHashMap::new, Collectors.toList()));

        System.out.print("=========================== //获取房间信息" + lwgyBaseBedT);
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();

        //按照房间信息循环
        lwgyBaseBedT.forEach((key, value) -> {
            Map<String, Object> map1 = new HashMap<>();


            List<ImportStuHotel> list = value;
            list.stream().forEach(p -> {
                map1.put("campusName", p.getCampusName());
                map1.put("roomName", p.getBuildingName());
                map1.put("className", p.getStudentClass());
                for (int i = 1; i <= info; i++) {
                    if (p.getBedName().contains(i + "")) {
                        map1.put(i + "link_num", p.getStudentNumber());
                        map1.put(i + "link_name", p.getStudentName());
                    }
                }

            });

            dataList.add(map1);
        });

        //获取最大床位数
        int bedsize = info;
        List<ExcelExportEntity> entityList = ExcelImport.ExcelImportUtil(bedsize);

        Workbook wb = ExcelExportUtil.exportExcel(new ExportParams(null, "sheetName"), entityList, dataList);

        try {
            String fileName = "用户信息表";
            OutputStream output = response.getOutputStream();

            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "utf-8") + ".xls");
            wb.write(output);
            output.close();


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 通过excel导入数据进行退宿。表格中只有两种信息，学号，姓名
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcelUrlToTs", method = RequestMethod.POST)
    public Result<?> importExcelUrlToTs(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        MultipartFile file = fileMap.get("file");
        try {
            ImportParams params = new ImportParams();
            params.setNeedSave(true);
            params.setTitleRows(1);// 设置第一行为标题
            params.setHeadRows(2);// 设置第一行为标题
            List<ImportLwgyStu> list = ExcelImportUtil.importExcel(file.getInputStream(), ImportLwgyStu.class, params);
            List<String> numbers = new ArrayList<>(list.size());
            list.stream().forEach(item -> {
                numbers.add(item.getStuNumber());
            });

            List<LwgyHotelArrangement> listT = lwgyHotelArrangementService.queryStuBedByNumberList(numbers);
            if (oConvertUtils.isNotEmpty(listT) && listT.size() > 0) {
                String ids = "";
                LwgyHotelHistory lwgyHotelHistory;
                List<LwgyHotelHistory> arrangementList = new ArrayList<>();
                LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                for (LwgyHotelArrangement stu : listT) {
                    ids += stu.getBeforeBed() + ",";
                    lwgyHotelHistory = JSON.parseObject(JSON.toJSONString(stu), LwgyHotelHistory.class);

                    lwgyHotelHistory.setPersonId(stu.getStudentId());
                    lwgyHotelHistory.setCreateBy(sysUser.getUsername());
                    arrangementList.add(lwgyHotelHistory);
                }
                lwgyHotelArrangementService.cleanBed(ids);//批量清空住宿
                lwgyHotelHistoryService.saveBatch(arrangementList);//批量存储退宿记录
            }


            return Result.OK("成功退宿" + listT.size() + "名学生");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.OK();

    }

    /**
     * 通过excel导入
     * 有重复床位信息和重复住宿信息时，改功能无法用；
     *
     * @param request
     * @param response
     * @return
     */
/*    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        MultipartFile file = fileMap.get("file");
        try {
            ImportParams params = new ImportParams();
            params.setNeedSave(true);
            params.setTitleRows(1);//设置第一行为标题
            params.setHeadRows(2);//第二行为表头
            List<ImportStuHotel> list = ExcelImportUtil.importExcel(file.getInputStream(), ImportStuHotel.class, params);
            //导入信息添加学生id
            List<LwgyHotelHistory> arrangementList = new ArrayList<>();
            List<LwgyBaseBed> bedList = new ArrayList<>();
            LwgyBaseBed lwgyBaseBed;
            LwgyHotelHistory lwgyHotelHistory;

            list = lwgyHotelArrangementService.selectStudentIdList(list);


            //获取导入床位的当前住宿情况
            List<LwgyBaseBed> listBed = lwgyHotelArrangementService.selectBedByStuList(list);


            if (list.size() > 0) {
                String tsIds = "";
                String tsStuIds = "";
                String insertStuIds = "";
                for (ImportStuHotel item : list) {
                    for (LwgyBaseBed item2 : listBed) {
                        if (item.getCampusName().equals(item2.getCampusName())
                                && item.getBuildingName().equals(item2.getBuildingName())
                                && item.getUnitName().equals(item2.getUnitName())
                                && item.getRoomName().equals(item2.getRoomName())
                                && item.getBedName().equals(item2.getBedName())) {


                            lwgyBaseBed = new LwgyBaseBed();
                            lwgyHotelHistory = new LwgyHotelHistory();
                            if (oConvertUtils.isNotEmpty(item2.getStudentId())
                                    && oConvertUtils.isEmpty(item.getStudentId())) {
                                tsIds += item2.getId() + ",";
                                tsStuIds += item2.getStudentId() + ",";
                                System.out.print("退宿---------------------------" + item2.getId());
                            }
                            //系统非空，表非空，但是系统中用户与表中不一致--退+住
                            if (oConvertUtils.isNotEmpty(item2.getStudentId())
                                    && oConvertUtils.isNotEmpty(item.getStudentId())
                                    && !item.getStudentId().equals(item2.getStudentId())) {
                                tsIds += item2.getId() + ",";
                                tsStuIds += item2.getStudentId() + ",";
                                insertStuIds += item.getStudentId() + ",";
                                lwgyBaseBed.setId(item2.getId());
                                lwgyBaseBed.setStudentId(item.getStudentId());
                                bedList.add(lwgyBaseBed);
                                lwgyHotelHistory.setBehavior("choose_bed");
                                lwgyHotelHistory.setPersonId(item.getStudentId());
                                lwgyHotelHistory.setAfterBed(item2.getId());
                                arrangementList.add(lwgyHotelHistory);


                            }
                            //系统空，表非空，住
                            if (oConvertUtils.isEmpty(item2.getStudentId())
                                    && oConvertUtils.isNotEmpty(item.getStudentId())) {

                                insertStuIds += item.getStudentId() + ",";
                                lwgyBaseBed.setId(item2.getId());
                                lwgyBaseBed.setStudentId(item.getStudentId());
                                bedList.add(lwgyBaseBed);

                                lwgyHotelHistory.setBehavior("choose_bed");
                                lwgyHotelHistory.setPersonId(item.getStudentId());
                                lwgyHotelHistory.setAfterBed(item2.getId());
                                arrangementList.add(lwgyHotelHistory);
                            }


                        }
                    }
                }

                //要安排住宿的学生之前是否有住宿信息
                List<LwgyBaseBed> bedListByStu = lwgyHotelArrangementService.selectStuBedByStuId(insertStuIds);
                if (oConvertUtils.isNotEmpty(bedListByStu)) {
                    for (LwgyBaseBed item : bedListByStu) {
                        tsIds += item.getId() + ",";
                        tsStuIds += item.getStudentId() + ",";
                    }
                }

                System.out.print("退宿---------------------------" + tsIds);
                if (tsIds.length() > 0) {
                    List<LwgyHotelHistory> arrangementList2 = lwgyHotelArrangementService.leaveBedHistory(tsStuIds);
                    lwgyHotelArrangementService.cleanBed(tsIds);//批量清空住宿
                    lwgyHotelHistoryService.saveBatch(arrangementList2);//批量存储退宿记录
                }
                if (bedList.size() > 0) {
                    lwgyBaseBedService.updateBatchById(bedList);//更新入住信息
                    lwgyHotelHistoryService.saveBatch(arrangementList);//保存历史记录
                }
            }
            return Result.OK("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.OK();
    }*/


}
